package com.yzq.os.spider.v.service.inter;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.yzq.os.spider.v.domain.WebSite;
import com.yzq.os.spider.v.domain.ListPageConfig;
import com.yzq.os.spider.v.domain.LogRecord;
import com.yzq.os.spider.v.domain.SearchEngine;
import com.yzq.os.spider.v.service.http.HttpClientService;
import com.yzq.os.spider.v.util.Encode;

/**
 * 外部系统接口
 * @author 苑志强(xingyu_yzq@163.com)
 *
 */
@Service
public class OuterSystemService {

	private static Logger logger = Logger.getLogger(OuterSystemService.class);

	@Value("${app.url.website.interface}")
	private String webSiteInterfaceUrl;

	@Autowired
	private HttpClientService httpClientService;

	private static List<WebSite> sites;

	public List<WebSite> getWebsites() {
		if (sites == null) {
			synchronized (OuterSystemService.class) {
				try {
					initWebsites();
				} catch (Exception e) {
					logger.error("", e);
				}
			}
		}
		return sites;
	}

	private void initWebsites() throws Exception {
		String xml = httpClientService.doGetRequest(webSiteInterfaceUrl, Encode.UTF8, false, null);
		Document doc = DocumentHelper.parseText(xml);
		@SuppressWarnings("rawtypes")
		List nodes = doc.selectNodes("//websites/website");
		sites = new ArrayList<WebSite>();
		for (int i = 0; i < nodes.size(); i++) {
			Element element = (Element) nodes.get(i);
			String id = element.attributeValue("id");
			String name = element.attributeValue("name");
			sites.add(new WebSite(Integer.parseInt(id), name));
		}
		// sort websites list
		final Collator pinyinCmp = Collator.getInstance(Locale.CHINA);
		Collections.sort(sites, new Comparator<WebSite>() {
			@Override
			public int compare(WebSite o1, WebSite o2) {
				return pinyinCmp.compare(o1.getName(), o2.getName());
			}
		});
		logger.info("Inited websites from:[" + webSiteInterfaceUrl + "]");
	}

	/**
	 * 根据网站ID获取网站对象
	 * @param siteId
	 * @return
	 */
	public WebSite getWebsite(int siteId) {
		WebSite site = null;
		List<WebSite> sites = getWebsites();
		for (WebSite _site : sites) {
			if (_site.getId() == siteId) {
				site = _site;
				break;
			}
		}
		return site;
	}

	public void clearWebsites() {
		sites = null;
		logger.info("Clear cache websites.");
	}

	public void setEngineWebsiteNames(List<SearchEngine> engines) {
		if (CollectionUtils.isNotEmpty(engines)) {
			for (SearchEngine engine : engines) {
				WebSite site = getWebsite(engine.getWebsiteId());
				if (site != null) {
					engine.setWebsiteName(site.getName());
				}
			}
		}
	}

	public void setListPageWebsiteNames(List<ListPageConfig> configs) {
		if (CollectionUtils.isNotEmpty(configs)) {
			for (ListPageConfig config : configs) {
				WebSite site = getWebsite(config.getWebsiteId());
				if (site != null) {
					config.setWebsiteName(site.getName());
				}
			}
		}

	}

	public void setLogWebsiteNames(List<LogRecord> records) {
		if (CollectionUtils.isNotEmpty(records)) {
			for (LogRecord record : records) {
				WebSite site = getWebsite(record.getWebsiteId());
				if (site != null) {
					record.setWebsiteName(site.getName());
				}
			}
		}
	}
}
